package com.hanc.pay.task;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.hanc.pay.entity.OrderInfo;
import com.hanc.pay.entity.PaymentInfo;
import com.hanc.pay.enums.OrderStatus;
import com.hanc.pay.enums.PayType;
import com.hanc.pay.enums.wxpay.WxTradeState;
import com.hanc.pay.service.OrderInfoService;
import com.hanc.pay.service.PaymentInfoService;
import com.hanc.pay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.swing.*;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class WxPayTask {

    @Resource
    private OrderInfoService orderInfoService;

    @Resource
    private WxPayService wxPayService;

    @Resource
    private PaymentInfoService paymentInfoService;

    /**
     * 定时查单任务
     * 0/30 每隔30秒执行一次定时任务  查看创建时间超过五分钟 未支付的订单
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void queryTask() throws Exception {
        log.info("定时任务开始执行。。。。。");

        //查询下单超过五分钟的条件
        Instant minus = Instant.now().minus(Duration.ofMinutes(5));

        //查询下单超过五分钟的未支付订单
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_status", OrderStatus.NOTPAY.getType());
        wrapper.le("create_time",minus);
        List<OrderInfo> list = orderInfoService.list(wrapper);
        for (OrderInfo orderInfo : list) {
            String orderNo = orderInfo.getOrderNo();
            log.info("超过创建时间五分钟的订单号==>{}",orderNo);

            //调用查单接口
            String result = wxPayService.queryOrder(orderNo);
            Map resultMap = new Gson().fromJson(result, HashMap.class);
            Object tradeState = resultMap.get("trade_state");
            if (WxTradeState.SUCCESS.getType().equals(tradeState)){
                log.info("核实订单已支付 ==> {}",orderNo);

                //修改订单状态
                orderInfo.setOrderStatus(OrderStatus.SUCCESS.getType());
                orderInfoService.updateById(orderInfo);

                //新增支付记录
                //获取订单金额
                Map<String,Object> amount = (Map) resultMap.get("amount");
                //用户支付金额，整型，单位为分。（指使用优惠券的情况下，这里等于总金额-优惠券金额）
                Integer payerTotal = ((Double)amount.get("payer_total")).intValue();
                //组装新增参数
                PaymentInfo paymentInfo = new PaymentInfo(
                        orderInfo.getOrderNo(),
                        (String) resultMap.get("transaction_id "),//微信支付订单号
                        PayType.WXPAY.getType(),//支付类型
                        (String) resultMap.get("trade_type"),//交易类型
                        (String) resultMap.get("trade_state "),//交易状态
                        payerTotal,//订单金额
                        result
                );
                paymentInfo.setCreateTime(new Date());
                paymentInfo.setUpdateTime(new Date());
                paymentInfoService.save(paymentInfo);
            }
            if (WxTradeState.NOTPAY.getType().equals(tradeState)){
                log.info("核实订单未支付 ==> {}，调用关单",orderNo);
                //调用关单接口
                wxPayService.closeNativePay(orderNo);

                //修改订单状态为超时已关闭
                orderInfo.setOrderStatus(OrderStatus.CLOSED.getType());
                orderInfoService.updateById(orderInfo);

            }

        }
    }

}
